package com.cn.jasyptdbtwo.service.impl;


import com.cn.jasyptdbtwo.dao.PriceListMapper;
import com.cn.jasyptdbtwo.pojo.PriceList;
import com.cn.jasyptdbtwo.service.PriceListService;
import com.cn.jasyptdbtwo.util.HttpResult;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * TODO
 *
 * @author 江
 * @date 2021/9/13 下午 14:53
 */
@Service
public class PriceListImpl implements PriceListService {

    @Autowired
    PriceListMapper priceListMapper;

    /**
     * 读取数据库
     *
     * @author 江
     * @date 2021/9/13 下午 14:53
     */
    @Override
    public HttpResult selectAllPriceList(int page, int pageSize) {
        List<PriceList> priceLists = null;
        com.github.pagehelper.PageInfo pageInfo1 = null;
        try {
            PageHelper.startPage(page, pageSize);
            priceLists = priceListMapper.selectAllPriceList();
            pageInfo1 = new com.github.pagehelper.PageInfo(priceLists, pageSize);
        } catch (Exception e) {
//            e.printStackTrace();
            return HttpResult.newError("查询失败！");
        }
        return HttpResult.newSuccess().add("data", pageInfo1);
    }

    /**
     *  TODO 测试事务  @Transactional的事务都是自动提交的(commit)，遇到异常时回滚(rollback)
     * @Param : exceptionFlag 是否产生 bug
     * @return HttpResult
     * @Author 江
     * @Date 2021/9/24 下午 15:22
     */
    @Transactional
    @Override
    public HttpResult testTransactional(boolean exceptionFlag) {
        System.out.println("删除前 = " + priceListMapper.selectCountPriceList(91));
        priceListMapper.deletePriceList(91);
        System.out.println("删除后 = " + priceListMapper.selectCountPriceList(91));
        PriceList priceList = new PriceList();
        priceList.setId(91);
        priceList.setDescribe("1%");
        priceList.setName("relatedcosts");
        priceList.setItems("item");
        priceList.setRemarks("mark");
        priceList.setStatus(1);
        priceList.setUnit("unit");
        priceList.setUnitprice("10wan");
        System.out.println("priceList = " + priceList);
        priceListMapper.insterPriceList(priceList);
        // 重复的主键，DB会报主键冲突的异常
        if (exceptionFlag) {
            priceList.setName("doublePrimaryKey");
            priceListMapper.insterPriceList(priceList);
        }

        return HttpResult.newSuccess();
    }


}
